<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>{{ isEdit ? '编辑礼品' : '新增礼品' }}</span>
          <el-button type="text" @click="showHelp = !showHelp">
            <el-icon><QuestionFilled /></el-icon>
            帮助
          </el-button>
        </div>
      </template>

      <!-- 帮助信息 -->
      <div v-if="showHelp" class="help-section">
        <el-alert title="礼品类型说明" type="info" :closable="false" show-icon>
          <template #default>
            <div class="help-content">
              <p>
                <strong>会员类型：</strong>
                用户兑换后可获得会员权限，需要设置会员天数（1-365天）
              </p>
              <p>
                <strong>实物类型：</strong>
                用户兑换后可获得实物礼品，后端自动处理配送等流程
              </p>
              <p>
                <strong>头饰类型：</strong>
                用户兑换后可获得头饰奖励，需要选择具体的头饰
              </p>
            </div>
          </template>
        </el-alert>
      </div>

      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" style="max-width: 600px" class="gift-form">
        <el-form-item label="礼品图片" prop="imageUrl">
          <uploadImg :imageUrl="form.imageUrl" @success="uploadSuccess" @delete="deleteImage" />
          <div class="form-tip">请上传礼品图片，建议尺寸为200x200像素，格式：jpg/png，大小≤2MB</div>
        </el-form-item>

        <el-form-item label="礼品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入礼品名称" maxlength="50" show-word-limit />
        </el-form-item>

        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型" @change="handleTypeChange">
            <el-option label="会员" value="vip">
              <div class="type-option">
                <span>会员</span>
                <el-tooltip content="用户兑换后可获得会员权限，需要设置会员天数" placement="top">
                  <el-icon style="margin-left: 8px; color: #909399"><QuestionFilled /></el-icon>
                </el-tooltip>
              </div>
            </el-option>
            <el-option label="实物" value="real">
              <div class="type-option">
                <span>实物</span>
                <el-tooltip content="用户兑换后可获得实物礼品，后端自动处理" placement="top">
                  <el-icon style="margin-left: 8px; color: #909399"><QuestionFilled /></el-icon>
                </el-tooltip>
              </div>
            </el-option>
            <el-option label="头饰" value="headwear">
              <div class="type-option">
                <span>头饰</span>
                <el-tooltip content="用户兑换后可获得头饰奖励，需要选择具体头饰" placement="top">
                  <el-icon style="margin-left: 8px; color: #909399"><QuestionFilled /></el-icon>
                </el-tooltip>
              </div>
            </el-option>
          </el-select>
        </el-form-item>

        <!-- 会员时间输入 -->
        <div v-if="form.type === 'vip'" class="type-field">
          <el-form-item label="会员时间" prop="vipTime">
            <el-input-number v-model="form.vipTime" :min="1" :max="365" placeholder="请输入会员天数" style="width: 200px" />
            <span style="margin-left: 10px; color: #909399">天</span>
            <div class="form-tip">请输入会员有效天数，范围：1-365天</div>
          </el-form-item>
        </div>

        <!-- 头饰选择 -->
        <div v-if="form.type === 'headwear'" class="type-field">
          <el-form-item label="选择头饰" prop="headwearId">
            <HeadwearSelector v-model="form.headwearId" @change="handleHeadwearChange" />
            <div class="form-tip">请选择要奖励的头饰</div>
          </el-form-item>
        </div>

        <el-form-item label="所属分类" prop="categoryId">
          <div class="category-select">
            <el-select v-model="form.categoryId" placeholder="请选择分类" style="width: 300px">
              <el-option v-for="item in categoryOptions" :key="item._id" :label="item.name" :value="item._id">
                <div class="category-option">
                  <span>{{ item.name }}</span>
                  <el-icon color="#333" @click.stop="handleDeleteCategory(item)"><Close /></el-icon>
                </div>
              </el-option>
            </el-select>
            <el-button type="primary" @click="showCategoryDialog = true" style="margin-left: 10px">新增分类</el-button>
          </div>
        </el-form-item>

        <el-form-item label="兑换金币" prop="coins">
          <el-input-number v-model="form.coins" :min="1" :max="999999" placeholder="请输入兑换金币数" :disabled="isEdit && hasExchangeRecord" />
          <div class="form-tip" v-if="isEdit && hasExchangeRecord">已有兑换记录，金币数不可修改</div>
        </el-form-item>

        <el-form-item label="补差金额" prop="price">
          <el-input-number v-model="form.price" :min="0" :max="9999.99" :precision="2" :step="0.01" placeholder="请输入补差金额" :disabled="isEdit && hasExchangeRecord" />
          <div class="form-tip" v-if="isEdit && hasExchangeRecord">已有兑换记录，补差金额不可修改</div>
        </el-form-item>

        <el-form-item label="库存数量" prop="stock">
          <el-input-number v-model="form.stock" :min="0" :max="999999" placeholder="请输入库存数量" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-switch v-model="form.status" :active-value="'active'" :inactive-value="'inactive'" active-text="上架" inactive-text="下架" />
        </el-form-item>

        <el-form-item label="备注" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入备注信息" maxlength="100" show-word-limit />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="submitting">保存</el-button>
          <el-button @click="resetForm" :disabled="submitting">重置</el-button>
          <el-button @click="goBack" :disabled="submitting">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 新增分类弹窗 -->
    <el-dialog v-model="showCategoryDialog" title="新增分类" width="500px" :close-on-click-modal="false">
      <el-form ref="categoryFormRef" :model="categoryForm" :rules="categoryRules" label-width="80px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryForm.name" placeholder="请输入分类名称" maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="categoryForm.sort" :min="0" :max="999" placeholder="请输入排序值" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="categoryForm.description" type="textarea" :rows="2" placeholder="请输入分类描述" maxlength="100" show-word-limit />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCategoryDialog = false">取消</el-button>
          <el-button type="primary" @click="submitCategoryForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除分类确认弹窗 -->
    <el-dialog v-model="showDeleteDialog" title="删除分类" width="400px" :close-on-click-modal="false">
      <div class="delete-confirm">
        <el-icon class="warning-icon"><Warning /></el-icon>
        <p>
          确定要删除分类 "
          <strong>{{ selectedCategoryName }}</strong>
          " 吗？
        </p>
        <p class="warning-text">删除后无法恢复，请谨慎操作！</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDeleteDialog = false">取消</el-button>
          <el-button type="danger" @click="confirmDeleteCategory">确定删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
  import { ref, reactive, onMounted, computed } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { Warning, Close, QuestionFilled } from '@element-plus/icons-vue';
  import uploadImg from '@/components/uploadImg/index.vue';
  import { getGiftDetail, createGift, updateGift, getGiftCategories, createGiftCategory, deleteGiftCategory } from '@/api/gift';
  import HeadwearSelector from '@/components/HeadwearSelector/index.vue'; // Added import for HeadwearSelector

  const route = useRoute();
  const router = useRouter();

  const formRef = ref(null);
  const categoryFormRef = ref(null);
  const showCategoryDialog = ref(false);
  const showDeleteDialog = ref(false);
  const categoryOptions = ref([]);
  const selectedCategoryName = ref('');
  const selectedCategoryId = ref('');
  const hasExchangeRecord = ref(false);
  const submitting = ref(false); // 添加提交状态
  const showHelp = ref(false); // 新增帮助信息显示状态

  const isEdit = computed(() => route.params.id);

  const form = reactive({
    name: '',
    imageUrl: '',
    categoryId: '',
    coins: 1,
    price: 0,
    stock: 0,
    status: 'active', // 修改为字符串类型，与后端保持一致
    description: '',
    type: 'real', // Default type
    vipTime: 1, // Default VIP duration
    headwearId: '' // Default headwear ID
  });

  // 分类表单
  const categoryForm = reactive({
    name: '',
    sort: 0,
    description: ''
  });

  const rules = {
    name: [
      { required: true, message: '请输入礼品名称', trigger: 'blur' },
      { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
    ],
    imageUrl: [{ required: true, message: '请上传礼品图片', trigger: 'change' }],
    categoryId: [{ required: true, message: '请选择分类', trigger: 'change' }],
    coins: [
      { required: true, message: '请输入兑换金币数', trigger: 'blur' },
      { type: 'number', min: 1, message: '金币数必须大于0', trigger: 'blur' }
    ],
    price: [{ type: 'number', min: 0, message: '补差金额不能小于0', trigger: 'blur' }],
    stock: [
      { required: true, message: '请输入库存数量', trigger: 'blur' },
      { type: 'number', min: 0, message: '库存数量不能小于0', trigger: 'blur' }
    ],
    status: [{ required: true, message: '请选择状态', trigger: 'change' }],
    type: [{ required: true, message: '请选择礼品类型', trigger: 'change' }],
    vipTime: [
      {
        required: true,
        message: '请输入会员天数',
        trigger: 'blur',
        validator: (rule, value, callback) => {
          if (form.type === 'vip' && (!value || value < 1 || value > 365)) {
            callback(new Error('会员天数范围：1-365天'));
          } else {
            callback();
          }
        }
      }
    ],
    headwearId: [
      {
        required: true,
        message: '请选择头饰',
        trigger: 'change',
        validator: (rule, value, callback) => {
          if (form.type === 'headwear' && !value) {
            callback(new Error('请选择头饰'));
          } else {
            callback();
          }
        }
      }
    ]
  };

  const categoryRules = {
    name: [
      { required: true, message: '请输入分类名称', trigger: 'blur' },
      { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
    ],
    sort: [{ required: true, message: '请输入排序值', trigger: 'blur' }]
  };

  const getDetail = async id => {
    try {
      const response = await getGiftDetail(id);
      if (response.code === 200) {
        const data = response.data;
        Object.assign(form, {
          name: data.name,
          imageUrl: data.imageUrl,
          categoryId: data.categoryId,
          coins: data.coins,
          price: data.price || 0,
          stock: data.stock,
          status: data.status,
          description: data.description || '',
          type: data.type || 'real',
          vipTime: data.vipTime || 1,
          headwearId: data.headwearId || ''
        });
        // 检查是否有兑换记录
        hasExchangeRecord.value = data.exchangeCount > 0;
      }
    } catch (error) {
      console.error('获取礼品详情失败:', error);
      ElMessage.error('获取礼品详情失败');
    }
  };

  const getCategories = async () => {
    try {
      const response = await getGiftCategories();
      if (response.code === 200) {
        categoryOptions.value = response.data.list;
      }
    } catch (error) {
      console.error('获取分类列表失败:', error);
    }
  };

  const uploadSuccess = imageUrl => {
    form.imageUrl = imageUrl;
  };

  const deleteImage = () => {
    form.imageUrl = '';
  };

  const handleTypeChange = () => {
    // 清空类型相关的字段
    if (form.type !== 'vip') {
      form.vipTime = 1;
    }
    if (form.type !== 'headwear') {
      form.headwearId = '';
    }
  };

  const handleHeadwearChange = headwearId => {
    form.headwearId = headwearId;
  };

  const handleDeleteCategory = async item => {
    selectedCategoryName.value = item.name;
    selectedCategoryId.value = item._id; // 存储要删除的分类ID
    showDeleteDialog.value = true;
  };

  const confirmDeleteCategory = async () => {
    try {
      const response = await deleteGiftCategory(selectedCategoryId.value);
      if (response.code === 200) {
        ElMessage.success('分类删除成功');
        showDeleteDialog.value = false;

        // 如果删除的是当前选中的分类，则清空选择
        if (form.categoryId === selectedCategoryId.value) {
          form.categoryId = '';
          ElMessage.warning('已删除当前选中的分类，请重新选择');
        }

        // 重新获取分类列表
        await getCategories();
      } else {
        ElMessage.error(response.msg || '删除分类失败');
      }
    } catch (error) {
      console.error('删除分类失败:', error);
      ElMessage.error('删除分类失败');
    }
  };

  const submitForm = async () => {
    if (!formRef.value) return;

    await formRef.value.validate(async valid => {
      if (valid) {
        // 额外的数据验证
        if (form.type === 'vip' && (!form.vipTime || form.vipTime < 1 || form.vipTime > 365)) {
          ElMessage.error('会员天数必须在1-365天之间');
          return;
        }

        if (form.type === 'headwear' && !form.headwearId) {
          ElMessage.error('请选择头饰');
          return;
        }

        submitting.value = true; // 开始提交
        try {
          const submitData = {
            name: form.name, // 礼品名称
            imageUrl: form.imageUrl, // 礼品图片
            categoryId: form.categoryId, // 所属分类
            coins: form.coins, // 兑换金币
            price: form.price, // 补差金额
            stock: form.stock, // 库存数量
            status: form.status, // 状态
            description: form.description, // 备注
            sort: form.sort, // 排序
            type: form.type // 类型
          };

          // 根据类型添加特定字段
          if (form.type === 'vip') {
            submitData.vipTime = form.vipTime;
          } else if (form.type === 'headwear') {
            submitData.headwearId = form.headwearId;
          }
          // 实物类型不需要额外字段，后端处理

          let response;
          if (isEdit.value) {
            response = await updateGift(route.params.id, submitData);
          } else {
            response = await createGift(submitData);
          }

          if (response.code === 200) {
            ElMessage.success(isEdit.value ? '更新成功' : '创建成功');
            goBack();
          } else {
            ElMessage.error(response.msg || '操作失败');
          }
        } catch (error) {
          console.error('提交失败:', error);
          ElMessage.error('提交失败，请检查网络连接');
        } finally {
          submitting.value = false; // 结束提交
        }
      } else {
        ElMessage.warning('请完善表单信息');
      }
    });
  };

  const submitCategoryForm = async () => {
    if (!categoryFormRef.value) return;

    await categoryFormRef.value.validate(async valid => {
      if (valid) {
        try {
          const response = await createGiftCategory({
            name: categoryForm.name
          });
          if (response.code === 200) {
            ElMessage.success('分类创建成功');
            showCategoryDialog.value = false;
            // 重置分类表单
            categoryForm.name = '';
            categoryForm.sort = 0;
            categoryForm.description = '';
            // 重新获取分类列表
            await getCategories();
          } else {
            ElMessage.error(response.msg || '创建分类失败');
          }
        } catch (error) {
          console.error('创建分类失败:', error);
          ElMessage.error('创建分类失败');
        }
      }
    });
  };

  const goBack = () => {
    router.push('/gift/list');
  };

  const resetForm = () => {
    if (formRef.value) {
      formRef.value.resetFields();
    }
    // 重置表单数据
    Object.assign(form, {
      name: '',
      imageUrl: '',
      categoryId: '',
      coins: 1,
      price: 0,
      stock: 0,
      status: 'active',
      description: '',
      type: 'real',
      vipTime: 1,
      headwearId: ''
    });
  };

  onMounted(async () => {
    await getCategories();
    if (isEdit.value) {
      await getDetail(route.params.id);
    } else {
      // 新增时设置默认值
      form.type = 'real';
      form.status = 'active';
      form.coins = 1;
      form.price = 0;
      form.stock = 0;
      form.vipTime = 1;
      form.headwearId = '';
    }
  });
</script>

<style scoped>
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .category-select {
    display: flex;
    align-items: center;
  }

  .form-tip {
    font-size: 12px;
    color: #909399;
    margin: 0 0 0 20px;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }

  .delete-confirm {
    text-align: center;
    padding: 20px 0;
  }

  .warning-icon {
    font-size: 48px;
    color: #e6a23c;
    margin-bottom: 16px;
  }

  .warning-text {
    color: #f56c6c;
    font-size: 14px;
    margin-top: 8px;
  }

  .category-option {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
  }

  .delete-btn {
    margin-left: 8px;
    flex-shrink: 0;
  }

  /* 类型相关字段样式 */
  .type-field {
    background-color: #f8f9fa;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    border-left: 4px solid #409eff;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }

  .type-field .el-form-item {
    margin-bottom: 16px;
  }

  .type-field .el-form-item:last-child {
    margin-bottom: 0;
  }

  .type-field .el-form-item__label {
    font-weight: 600;
    color: #303133;
  }

  .type-option {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
  }

  .type-option span {
    font-weight: 500;
  }

  /* 帮助信息样式 */
  .help-section {
    margin-bottom: 20px;
    padding: 15px;
    background-color: #f0f9eb;
    border-radius: 8px;
    border: 1px solid #e1f3d8;
  }

  .help-content p {
    margin-bottom: 8px;
    line-height: 1.6;
  }

  .help-content strong {
    color: #67c23a;
  }

  /* 响应式设计 */
  @media (max-width: 768px) {
    .gift-form {
      max-width: 100% !important;
    }

    .gift-form .el-form-item__label {
      width: 100px !important;
    }

    .type-field {
      padding: 16px;
      margin-bottom: 16px;
    }

    .category-select {
      flex-direction: column;
      align-items: flex-start;
    }

    .category-select .el-button {
      margin-left: 0;
      margin-top: 10px;
    }
  }
</style>
